﻿using UnityEngine;
using System.Collections;

public class TestManager : MonoBehaviour {

	public static float latitude { get; private set; }
	public static float longitude { get; private set; } 


	void Start () 
	{
		latitude = 0;
		longitude = 0;
		UpdateLocation();
	}

	void UpdateLocation () 
	{
		StopAllCoroutines();
		StartCoroutine(GetLocation());
	}

	void OnGUI()
	{
		if(GUI.Button(new Rect(120, 20, 100, 30), "UpdateLocation"))
		{
			UpdateLocation();
		}
	}

	void Update()
	{
		if(Input.GetKeyDown(KeyCode.Escape))
		{
			Application.Quit();
		}
	}

	private IEnumerator GetLocation() 
	{
		if (!Input.location.isEnabledByUser)
			yield return null;

		Input.location.Start();
		int maxWait = 20;
		while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0) {
			yield return new WaitForSeconds(1);
			maxWait--;
		}
		if (maxWait < 1) {
			print("Timed out");
			yield return null;
		}
		if (Input.location.status == LocationServiceStatus.Failed) {
			print("Unable to determine device location");
			yield return null;
		} else
		{
			latitude = Input.location.lastData.latitude;
			longitude = Input.location.lastData.longitude;
			print("Location: " + Input.location.lastData.latitude + " " + Input.location.lastData.longitude + " " + Input.location.lastData.altitude + " " + Input.location.lastData.horizontalAccuracy + " " + Input.location.lastData.timestamp);
		}
		Input.location.Stop();
	}
}
